﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChapterX.Common;
using ChapterX.Data.DigitizationDSTableAdapters;
using System.Data;
using ChapterX.Data;
using ChapterX.BusinessFacade;

namespace ChapterX.Auth.Librarian
{
    public partial class ChapterList : ChapterX.Model.PageBase
    {

        protected int DigiStatus;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int bookId;
                if (Utils.HasValue(Request.QueryString[QueryKeys.BOOK_ID]) &&
                    Int32.TryParse(Utils.GetValue(Request.QueryString[QueryKeys.BOOK_ID]), out bookId))
                {
                    this.hl_AddChapter.NavigateUrl = String.Format("~/Auth/Librarian/ChapterEntry.aspx?{0}={1}",
                        QueryKeys.BOOK_ID, bookId.ToString());
                    
                    this.hf_BookId.Value = bookId.ToString();

                    DigitizationViewTableAdapter adapter = new DigitizationViewTableAdapter();

                    DataTable table = adapter.GetDigitizationByBookIdFromView(bookId);
                    if(table != null && table.Rows.Count > 0)
                    {
                        DataRow row = table.Rows[0];

                        Int32.TryParse(row["DigitizationStatus"].ToString(), out DigiStatus);

                        this.l_DigiStatus.Text = String.Format("状态为：{0}", CommonDefinition.getStringDigitizationStatus(DigiStatus));
                        if (DigiStatus != (int)CommonDefinition.DigitizationStatus.digitized)
                        {
                            this.l_DigiStatus.Text = String.Format("{0}，{1}", this.l_DigiStatus.Text, "请确认数字化");
                            this.btn_ConfirmDigi.Visible = true;
                        }
                        else
                            this.btn_ConfirmDigi.Visible = false;
                    }
                }
            }
        }

        protected void btn_ConfirmDigi_Click(object sender, EventArgs e)
        {
            DigitizationSystem ds = new DigitizationSystem();

            try
            {
                int bookId = Int32.Parse(this.hf_BookId.Value);

                bool result = ds.UpdateDigitizationStatus(bookId, (int)CommonDefinition.DigitizationStatus.digitized);
            
                if (result)
                    SetInfoMessage("确认数字化成功");
                else
                    SetErrorMessage("确认数字化失败，请重试");
            }
            catch(Exception ex)
            {
                Logger.Log(ex);
                SetErrorMessage("确认数字化失败，请重试");
            }
        }
    }
}
